package com.example.http.two

import android.os.Build
import android.util.Log
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.Buffer
import org.json.JSONObject
import retrofit2.Invocation
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Random
import java.util.concurrent.atomic.AtomicInteger


class HttpMallHeaderInterceptor:Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originRequest = chain.request()
        val originBuilder = originRequest.newBuilder()
        //0.添加统一请求头

        //1.判断是否为post请求，
        if(originRequest.method == "POST"){
            //2.若为post请求，获得请求体
            val body = originRequest.body
            //3.解析获得MallApiService里面service
            var service:String = ""
            val tag = originRequest.tag(Invocation::class.java)
            if(tag != null){
                val annotation = tag.method().getAnnotation(MallApiService::class.java)
                if(annotation != null){
                    service =  annotation.service
                }
            }
            Log.d("HttpMallHeaderInterceptor", "调用服务类型->$service")
            //4.在原来请求体的基础上添加一个service键值对
            val jsonBody = bodyToString(body)
            val jsonObject = JSONObject(jsonBody)
            jsonObject.put("service",service)
            jsonObject.put("channel", "ANDROID")
            jsonObject.put("token", "")
            jsonObject.put("requestNo",genRequestNo() )
            jsonObject.put("version", "1.0")
            jsonObject.put("partnerId", PARTNER_ID)
            val newBody = stringToBody(jsonObject.toString())
            originBuilder.post(newBody)

            //5.添加请求头
            //生成sign：签名规则和后台服务器端一致
            val sign = createSign(newBody)
            originBuilder.addHeader("Content-Language","zh-ch")
                .addHeader("platform", "ANDROID")
                .addHeader("meid","")
                .addHeader("version","1.0.0")
                .addHeader("phoneModel", Build.BRAND + "_" + Build.MODEL)
                //sign签名
                .addHeader("x-api-sign",sign)//签名
                .addHeader("x-api-signType", "MD5") //签名加密方式
                .addHeader("x-api-accessKey","23022113430907CF0113")//访问密钥
        }

        val newRequest = originBuilder.build()
        return chain.proceed(newRequest)



    }

    /**
     * 生成签名
     */
    private fun createSign(newBody: RequestBody): String {
        val params = bodyToString(newBody) //请求体参数
        val key = "6eef7179f83aea3986f7dd9be4c5cd8a" //密钥盐
        val buffer = Buffer()
        buffer.write(params.toByteArray(StandardCharsets.UTF_8))
        buffer.write(key.toByteArray(StandardCharsets.UTF_8))
        return buffer.md5().hex()
    }

    private fun stringToBody(str:String):RequestBody{
        val mediaType = "application/json; charset=utf-8".toMediaType()
        return str.toRequestBody(mediaType)
    }

    /**
     * body-->json字符串
     */

    private fun bodyToString(requestBody:RequestBody?):String{
        val buffer = Buffer()
        try {
            requestBody?.writeTo(buffer)
        }catch (e:Exception){
            return "something error,when show requestBody"
        }
        return buffer.readUtf8()

    }
    companion object{
        val _counter: AtomicInteger = AtomicInteger(0)
        val PARTNER_ID = "23022113430907CF0113"
    }


    // 生成随机请求号
    private fun genRequestNo(): String {
        return SimpleDateFormat("yyyyMMddHHmmssSSS").format(Date()) + Random().nextInt(
         HttpMallHeaderInterceptor._counter.addAndGet(
                1
            )
        )
    }
}